package pl.edu.agh.lab2.sr.game;

import java.rmi.RemoteException;

import pl.edu.agh.lab2.sr.beans.InvalidUserException;
import pl.edu.agh.lab2.sr.player.IPlayer;

public class BattleshipGame implements IBattleshipGame {

	private static final long serialVersionUID = -6105364710063695287L;
	private IPlayer player1;
	private IPlayer player2;

	private GameMap map1;

	private GameMap map2;

	private int gameId;

	@Override
	public IPlayer getPlayer2() {
		return player2;
	}

	@Override
	public IPlayer getPlayer1() {
		return player1;
	}

	public BattleshipGame(IPlayer player1, int gameId) throws RemoteException {
		this.player1 = player1;
		this.map1 = new GameMap();
		this.map2 = new GameMap();
		this.gameId = gameId;
	}

	@Override
	public void start() throws RemoteException {
		System.out.println("Game started");
		if (player1 == null) {
			throw new IllegalStateException("player1 not set");
		}

		if (player2 == null) {
			throw new IllegalStateException("player2 is not set");
		}

		if (map1 == null) {
			throw new IllegalStateException("map1 is not set");
		}

		if (map2 == null) {
			throw new IllegalStateException("map2 is not set");
		}

		System.out.println("game started");
		player1.infoFromGame("game started");
		player2.infoFromGame("game started");
		player1.setAbout("ABOUT1");
		player2.setAbout("ABOUT2");

	}

	@Override
	public void finish() throws RemoteException {
		// TODO Auto-generated method stub
		System.out.println("Game finished");
	}

	@Override
	public void nextMove() throws RemoteException {
		// TODO Auto-generated method stub
		System.out.println("next move");
	}

	@Override
	public void addSecondPlayer(IPlayer player) throws RemoteException,
			InvalidUserException {
		if (player2 == null) {
			player2 = player;
			System.out.println("Added player2 to game: " + player2.toString());
		} else {
			System.err.println("player2 already assigned");
			throw new InvalidUserException("player2 already assigned");
		}

	}

	@Override
	public int getId() {
		return this.gameId;
	}

	@Override
	public void setMap(IPlayer player, GameMap map) {
		if (player == player1) {
			map1 = map;
			System.out.println("initialized map1");
		} else if (player == player2) {
			map2 = map;
			System.out.println("initialized map20");
		} else {
			System.out.println("error when nitializing map");
			throw new IllegalArgumentException("error when initializing map");
		}

	}

}
